package com.infomanager;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Browser;
import android.widget.Toast;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import java.io.File;
import android.widget.Toast;


import com.infomanager.model.FileModel;
import com.infomanager.util.FileUtil;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;

import java.util.ArrayList;
import java.util.List;

import java.io.File;


/**
 * Created by Jin on 2016/3/8.
 */
public class RNFileSearchModule extends ReactContextBaseJavaModule {

    public RNFileSearchModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }
    public FileUtil fileUtil = new FileUtil(getReactApplicationContext());
    public List<FileModel> fileList = new ArrayList<FileModel>();
    public MediaPlayer mediaPlayer = new MediaPlayer();
    public boolean isPlaying = false;




    @Override
    public String getName() {
        return "RNFileSearch";
    }
    @ReactMethod
    public void openLocalFile(String path){
       File file = new File(path);
       Intent intent = new Intent();
       intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
       intent.setAction(Intent.ACTION_VIEW);
       String type = getMIMEType(file);
       intent.setDataAndType(Uri.fromFile(file), type);
       try {
           getReactApplicationContext().startActivity(intent);
       }catch (Exception e){
           Toast.makeText(getReactApplicationContext(),"你没有相应的程序打开此类型文件",Toast.LENGTH_LONG).show();
       }

   }

    @ReactMethod
   public void openOnlineFile(String path,String filename){
        Intent intent = new Intent(Intent.ACTION_VIEW);
        String type = getMIMETypeByName(filename);
        Uri uri = Uri.parse(path);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
       intent.setAction(Intent.ACTION_VIEW);
        // Toast.makeText(getReactApplicationContext(),"url："+path,Toast.LENGTH_LONG).show();
        intent.setDataAndType(uri, type);
        try {
           getReactApplicationContext().startActivity(intent);
        }catch (Exception e){
           Toast.makeText(getReactApplicationContext(),"你没有相应的程序打开此类型文件",Toast.LENGTH_LONG).show();
        }    
  }

   private String getMIMEType(File file) {

       String type="*/*";
       String fName = file.getName();
       int dotIndex = fName.lastIndexOf(".");
       if(dotIndex < 0){
           return type;
       }
       String end=fName.substring(dotIndex,fName.length()).toLowerCase();
       if(end=="")return type;

       for(int i=0;i<MIME_MapTable.length;i++){
           if(end.equals(MIME_MapTable[i][0]))
               type = MIME_MapTable[i][1];
       }
       return type;
   }
   private String getMIMETypeByName(String filename) {

       String type="*/*";
       int dotIndex = filename.lastIndexOf(".");
       if(dotIndex < 0){
           return type;
       }
       String end=filename.substring(dotIndex,filename.length()).toLowerCase();
       if(end=="")return type;

       for(int i=0;i<MIME_MapTable.length;i++){
           if(end.equals(MIME_MapTable[i][0]))
               type = MIME_MapTable[i][1];
       }
       return type;
   }

   private final String[][] MIME_MapTable={
           {".3gp",    "video/3gpp"},
           {".apk",    "application/vnd.android.package-archive"},
           {".asf",    "video/x-ms-asf"},
           {".avi",    "video/x-msvideo"},
           {".bin",    "application/octet-stream"},
           {".bmp",    "image/bmp"},
           {".c",  "text/plain"},
           {".class",  "application/octet-stream"},
           {".conf",   "text/plain"},
           {".cpp",    "text/plain"},
           {".doc",    "application/msword"},
           {".docx",   "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
           {".xls",    "application/vnd.ms-excel"},
           {".xlsx",   "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
           {".exe",    "application/octet-stream"},
           {".gif",    "image/gif"},
           {".gtar",   "application/x-gtar"},
           {".gz", "application/x-gzip"},
           {".h",  "text/plain"},
           {".htm",    "text/html"},
           {".html",   "text/html"},
           {".jar",    "application/java-archive"},
           {".java",   "text/plain"},
           {".jpeg",   "image/jpeg"},
           {".jpg",    "image/jpeg"},
           {".js", "application/x-javascript"},
           {".log",    "text/plain"},
           {".m3u",    "audio/x-mpegurl"},
           {".m4a",    "audio/mp4a-latm"},
           {".m4b",    "audio/mp4a-latm"},
           {".m4p",    "audio/mp4a-latm"},
           {".m4u",    "video/vnd.mpegurl"},
           {".m4v",    "video/x-m4v"},
           {".mov",    "video/quicktime"},
           {".mp2",    "audio/x-mpeg"},
           {".mp3",    "audio/x-mpeg"},
           {".mp4",    "video/mp4"},
           {".mpc",    "application/vnd.mpohun.certificate"},
           {".mpe",    "video/mpeg"},
           {".mpeg",   "video/mpeg"},
           {".mpg",    "video/mpeg"},
           {".mpg4",   "video/mp4"},
           {".mpga",   "audio/mpeg"},
           {".msg",    "application/vnd.ms-outlook"},
           {".ogg",    "audio/ogg"},
           {".pdf",    "application/pdf"},
           {".png",    "image/png"},
           {".pps",    "application/vnd.ms-powerpoint"},
           {".ppt",    "application/vnd.ms-powerpoint"},
           {".pptx",   "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
           {".prop",   "text/plain"},
           {".rc", "text/plain"},
           {".rmvb",   "audio/x-pn-realaudio"},
           {".rtf",    "application/rtf"},
           {".sh", "text/plain"},
           {".tar",    "application/x-tar"},
           {".tgz",    "application/x-compressed"},
           {".txt",    "text/plain"},
           {".wav",    "audio/x-wav"},
           {".wma",    "audio/x-ms-wma"},
           {".wmv",    "audio/x-ms-wmv"},
           {".wps",    "application/vnd.ms-works"},
           {".xml",    "text/plain"},
           {".z",  "application/x-compress"},
           {".zip",    "application/x-zip-compressed"},
           {"",        "*/*"}
   };

    @ReactMethod
    public void openFile(String url,String base,String type){

        Intent i = new Intent(Intent.ACTION_VIEW);
        Bundle bundle = new Bundle();
        bundle.putString("Authorization",base);
        i.putExtra(Browser.EXTRA_HEADERS, bundle);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.parse(url),type);
        getReactApplicationContext().startActivity(i);
    }

    @ReactMethod
    public void getImageResult(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    fileList = fileUtil.getImage();
                    WritableArray array = Arguments.createArray();

                    for(int i=0;i<fileList.size();i++){
                        WritableMap params = Arguments.createMap();
                        params.putString("thumbnail",fileList.get(i).thumbnail);
                        params.putString("title",fileList.get(i).title);
                        params.putString("year",fileList.get(i).year);
                        params.putString("mimeType",fileList.get(i).mimeType);
                        params.putString("filePath",fileList.get(i).filePath);
                        params.putString("size",fileList.get(i).size);
                        params.putBoolean("selected",fileList.get(i).selected);
                        // params.putBoolean("onCloud",fileList.get(i).onCloud);
                        array.pushMap(params);
                    }

                    getReactApplicationContext()
                        .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                        .emit("ImageArray", array);//对应的javascript层的事件名为logInConsole，注
                } catch (Exception e) {
                        e.printStackTrace();
                }

            }
        }).start();
    }
    @ReactMethod
    public void getWpsResult(){

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    fileList = fileUtil.getWPS();
                    WritableArray array = Arguments.createArray();

                    for(int i=0;i<fileList.size();i++){
                        WritableMap params = Arguments.createMap();
                        params.putString("thumbnail",fileList.get(i).thumbnail);
                        params.putString("title",fileList.get(i).title);
                        params.putString("year",fileList.get(i).year);
                        params.putString("mimeType",fileList.get(i).mimeType);
                        params.putString("filePath",fileList.get(i).filePath);
                        params.putString("size",fileList.get(i).size);
                        params.putBoolean("selected",fileList.get(i).selected);
                        // params.putBoolean("onCloud",fileList.get(i).onCloud);
                        array.pushMap(params);
                    }

                    getReactApplicationContext()
                        .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                        .emit("WpsArray", array);//对应的javascript层的事件名为logInConsole，注
                } catch (Exception e) {
                         e.printStackTrace();
                }
            }
        }).start();

    }
    @ReactMethod
    public void getVideoResult(){
      new Thread(new Runnable() {
          @Override
          public void run() {
              try {
          fileList = fileUtil.getVideo();
          WritableArray array = Arguments.createArray();

          for(int i=0;i<fileList.size();i++){
              WritableMap params = Arguments.createMap();
              params.putString("thumbnail",fileList.get(i).thumbnail);
              params.putString("title",fileList.get(i).title);
              params.putString("year",fileList.get(i).year);
              params.putString("mimeType",fileList.get(i).mimeType);
              params.putString("filePath",fileList.get(i).filePath);
              params.putString("size",fileList.get(i).size);
              params.putBoolean("selected",fileList.get(i).selected);
              // params.putBoolean("onCloud",fileList.get(i).onCloud);
              array.pushMap(params);
          }

          getReactApplicationContext()
              .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
              .emit("VideoArray", array);//对应的javascript层的事件名为logInConsole，注

      } catch (Exception e) {
          e.printStackTrace();
      }
          }
      }).start();


    }
    @ReactMethod
    public void getAudioResult(){
      new Thread(new Runnable() {
        @Override
        public void run() {
          try {
            fileList = fileUtil.getAudio();
            WritableArray array = Arguments.createArray();

            for(int i=0;i<fileList.size();i++){
              WritableMap params = Arguments.createMap();
              params.putString("thumbnail",fileList.get(i).thumbnail);
              params.putString("title",fileList.get(i).title);
              params.putString("year",fileList.get(i).year);
              params.putString("mimeType",fileList.get(i).mimeType);
              params.putString("filePath",fileList.get(i).filePath);
              params.putString("size",fileList.get(i).size);
              params.putBoolean("selected",fileList.get(i).selected);
              // params.putBoolean("onCloud",fileList.get(i).onCloud);
              array.pushMap(params);
            }

            getReactApplicationContext()
            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
            .emit("AudioArray", array);//对应的javascript层的事件名为logInConsole，注

          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }).start();


    }
    @ReactMethod
    public void getPptResult(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    fileList = fileUtil.getPpt();
                    WritableArray array = Arguments.createArray();

                    for(int i=0;i<fileList.size();i++){
                    WritableMap params = Arguments.createMap();
                    params.putString("thumbnail",fileList.get(i).thumbnail);
                    params.putString("title",fileList.get(i).title);
                    params.putString("year",fileList.get(i).year);
                    params.putString("mimeType",fileList.get(i).mimeType);
                    params.putString("filePath",fileList.get(i).filePath);
                    params.putString("size",fileList.get(i).size);
                    params.putBoolean("selected",fileList.get(i).selected);
                    // params.putBoolean("onCloud",fileList.get(i).onCloud);
                    array.pushMap(params);
            }

            getReactApplicationContext()
                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit("PptArray", array);//对应的javascript层的事件名为logInConsole，注
        } catch (Exception e) {
            e.printStackTrace();
        }
            }
        }).start();
    }

    @ReactMethod
    public void getLabelResult(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    fileList = fileUtil.getLabel();
                    WritableArray array = Arguments.createArray();

                    for(int i=0;i<fileList.size();i++){
                    WritableMap params = Arguments.createMap();
                    params.putString("thumbnail",fileList.get(i).thumbnail);
                    params.putString("title",fileList.get(i).title);
                    params.putString("year",fileList.get(i).year);
                    params.putString("mimeType",fileList.get(i).mimeType);
                    params.putString("filePath",fileList.get(i).filePath);
                    params.putString("size",fileList.get(i).size);
                    // params.putBoolean("selected",fileList.get(i).selected);
                    // params.putBoolean("onCloud",fileList.get(i).onCloud);
                    array.pushMap(params);
            }

            getReactApplicationContext()
                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit("PptArray", array);//对应的javascript层的事件名为logInConsole，注
        } catch (Exception e) {
            e.printStackTrace();
        }
            }
        }).start();
    }

}
